import { _decorator, Component, Node, SpriteComponent, LabelComponent, loader, JsonAsset } from 'cc';
import Constants from '../data/Constans';
const { ccclass, property } = _decorator;


@ccclass('LoadingManager')
export class LoadingManager extends Component {
    @property(SpriteComponent)
    ProgressBar: SpriteComponent = null;

    @property(LabelComponent)
    UITips: LabelComponent = null;

    @property(LabelComponent)
    UIText: LabelComponent = null;

    // 进度条初始值
    progress: number = 0;
    preProgress: number = 0;
    resource: any = null;
    tips: any = [];
    timeCallBack: any = null;
    loadAdStatus: boolean = false;
    loginStaus: boolean = false;

    private _GameConfig = null;
    private _system = 'devtools';

    start() {
        this.tips = [
            "小提示：神笔点石成金(剑)",
            "小提示：氪金币升级神笔",
            "小提示：把敌人打下擂台，你就是最捣蛋的仔",
            "小提示：拼点击手速，练成小李飞刀",
        ]

        let count = 0
        this.timeCallBack = () => {
            if (count == 2) {
                count = 0
            }
            count += 1
            this.UITips.string = this.tips[count]
        }
        this.schedule(this.timeCallBack, 1);

        // 登录
        Constants.GameControl.Login();

        // 加载配置文件(魅族平台不适用远程配置表)
        Constants.API.getJsonConfig().then(res => {
            printLog('获取到配置文件', res);
            if (res.status && res.data.length > 0) {
                for (let index = 0; index < res.data.length; index++) {
                    if (res.data[index].versions == Constants.GameControl.getConfigVersion()) {
                        loader.load(res.data[index].config_file_path, (err, JsonAsset) => {
                            if (err) {
                                // 加载本地配置文件
                                printLog('加载本地配置文件', err);
                                this._loadingConfig();
                            } else {
                                // 加载远程配置文件
                                printLog('加载远程配置文件');
                                this._GameConfig = JsonAsset;
                                Constants.GameControl.setGameConfig(this._GameConfig);
                                this._loadingLobby();
                            }
                            this._init();
                        })
                        break;
                    }
                }

            } else {
                printLog('加载本地配置文件');
                this._loadingConfig();
                this._init();
            }
        });

        // 阿拉丁
        const key = this._system + '进入加载';
        const value = key;
        Constants.AldAnalytics.aldSendEvent(key, value);

        // cocos埋点
        Constants.CocosAnalytics.init(false);
        Constants.CocosAnalytics.onStarted({ name: '用户进入加载界面', values: { loadScene: '用户进入加载界面', } });
        // Constants.CocosAnalytics.loginStart();

        // 头条埋点
        Constants.TTAnalytics.reportAnalytics('loading', {});

    }

    private _loadingConfig() {
        loader.loadRes('config/GameConfig', JsonAsset, (err, jsonAsset) => {
            if (!err) {
                this._GameConfig = jsonAsset.json;
                Constants.GameControl.setGameConfig(this._GameConfig);
                this._loadingLobby();
            }
        });
    }

    private _init() {
        const initTask = () => {
            Constants.GameControl.setLocalStorage({ key: Constants.StorageName.GAME_TIMESTAMP, value: getYesterdayTimestamp() });
            Constants.GameControl.setLocalStorage({ key: Constants.StorageName.FIRST_STATE, value: false });
            Constants.GameControl.setLocalStorage({ key: Constants.StorageName.FIRST_START_GAME, value: false });
        }

        if (Constants.GameControl.getLocalStorage(Constants.StorageName.GAME_TIMESTAMP)) {
            const now = Math.round(new Date().getTime() / 1000);
            if (now > parseInt(Constants.GameControl.getLocalStorage(Constants.StorageName.GAME_TIMESTAMP))) {
                initTask();
            }
        } else {
            initTask();
        }
    }

    // 加载资源
    private _loadingLobby() {
        // cc.loader.loadResDir(
        //     "/prefab",
        //     this._onLoadProgressCallback.bind(this),
        //     this._onLoadCompleteCallback.bind(this),
        // )
    }

    //加载atlas资源进度
    private _onLoadProgressCallback(completedCount, totalCount, item) {
        let p = parseFloat(((completedCount / totalCount) - 0.02).toFixed(2));
        if (this.ProgressBar.fillRange < p) {
            this.ProgressBar.fillRange = p;
            let progress = (100 * completedCount / totalCount) - 2 < 0 ? 0 : (100 * completedCount / totalCount) - 2;
            this.UIText.string = progress.toFixed(0) + "%";
        }
    }

    //加载atlas资源完成
    private _onLoadCompleteCallback(error, resource) {
        let count = 0;
        let state = false;

        const key = this._system + '进入主页';
        const value = key;

        // 预加载场景
        // cc.director.preloadScene("Game", () => {
        //     state = true;
        //     this.ProgressBar.fillRange = 1;
        //     this.UIText.string = "100%";
        // });

        let callback = () => {
            count += 1;
            if (this._GameConfig && state) {
                this.unscheduleAllCallbacks();
                // cc.director.loadScene("Game");
                Constants.AldAnalytics.aldSendEvent(key, value);
                Constants.CocosAnalytics.onSuccess({ name: '进入游戏大厅', values: { loadScene: '进入游戏大厅', } });
                Constants.TTAnalytics.reportAnalytics('home', {});
            }
            

            if (count > 10) {
                this.unscheduleAllCallbacks();
                // cc.director.loadScene("Game");
                Constants.AldAnalytics.aldSendEvent(key, value);
                Constants.CocosAnalytics.onSuccess({ name: '进入游戏大厅', values: { loadScene: '进入游戏大厅', } });
                Constants.TTAnalytics.reportAnalytics('home', {});
            }
        }

        this.schedule(callback, 1);
    }
}
